// import 'fbasic.dart';

part of '../fhare.dart';

extension ListToMapExt<E> on Iterable<E> {
  Map<K, E> toMap<K>(K Function(E) block) {
    Map<K, E> map = {};
    for (E e in this) {
      map[block(e)] = e;
    }
    return map;
  }
}

extension NullableIterableExtensions22<T extends Object> on Iterable<T?> {
  List<T> get nonNullList => nonNulls.toList();
}

extension _MapGetOrPut<K, V> on Map<K, V> {
  // ignore: unused_element
  V getOrPut(K key, V Function() onMiss) {
    V? v = this[key];
    if (v != null) {
      return v;
    }
    V vv = onMiss();
    this[key] = vv;
    return vv;
  }
}

extension ListGenericEx<T> on List<T> {
  int? maxInt(int Function(T) block) {
    return this.map(block).maxValue();
  }
}

extension ListAvgInt on List<int> {
  double? avgValue() {
    int? m;
    for (int a in this) {
      if (m == null) {
        m = a;
      } else {
        m = m + a;
      }
    }
    if (m == null || this.isEmpty) return null;
    return m / this.length;
  }
}

extension ListAvgDouble on List<double> {
  double? avgValue() {
    double? m;
    for (double a in this) {
      if (m == null) {
        m = a;
      } else {
        m = m + a;
      }
    }
    if (m == null || this.isEmpty) return null;
    return m / this.length;
  }
}

extension ListSliceEx<T> on List<T> {
  T? get second => this.getOr(1);

  T? get third => this.getOr(2);

  T? get lastSecond => this.getOr(length - 2);

  List<T> slice(int start, int size) {
    if (start >= length) return [];
    if (start + size >= length) return sublist(start);
    return sublist(start, start + size);
  }

  List<T> removeAll(Predicate<T> p) {
    List<T> ls = this.filter(p);
    this.removeWhere(p);
    return ls;
  }

  T? removeFirst(Predicate<T> p) {
    int idx = this.indexWhere(p);
    if (idx < 0) return null;
    T item = this[idx];
    this.removeAt(idx);
    return item;
  }

  IntRange get indexes => length.indexes;
}
